// const { electronAPI } = require("@electron-toolkit/preload");
const { ipcRenderer, contextBridge } = require("electron");
const {
  peer,
  setRemote,
} = require("../../renderer/pages/control/peer-control");
// const setRemote = 1;
// const peer = 1;

// 创建带类型的ipcRenderer对象，暴露给渲染进程
const ipc = {
  // 发送消息到主进程（无返回值）
  send: (channel, ...args) => {
    ipcRenderer.send(channel, ...args);
  },
  // 调用主进程方法（有返回值）
  invoke: (channel, ...args) => {
    return ipcRenderer.invoke(channel, ...args);
  },
  // 监听主进程消息
  on: (channel, listener) => {
    ipcRenderer.on(channel, (_, ...args) => listener(...args));
    return () => {
      ipcRenderer.removeListener(channel, listener);
    };
  },
  // 移除所有监听器
  removeAllListeners: (channel) => {
    ipcRenderer.removeAllListeners(channel);
  },
  // 移除指定监听器
  removeListener: (channel, listener) => {
    ipcRenderer.removeListener(channel, listener);
  },
};

// 指示当前JavaScript上下文是否与其他上下文隔离运行。
if (process.contextIsolated) {
  try {
    // contextBridge.exposeInMainWorld("electron", electronAPI);
    // contextBridge.exposeInMainWorld("api", api);
    contextBridge.exposeInMainWorld("ipcRenderer", ipc);
    contextBridge.exposeInMainWorld("control", {
      // peer: peer,
      on: (event, listener) => peer.on(event, listener),
      emit: (event, ...args) => peer.emit(event, ...args),
      setRemote: setRemote,
    });
  } catch (error) {
    console.error(error);
  }
} else {
  // @ts-ignore (define in dts)
  // window.electron = electronAPI;
  // @ts-ignore (define in dts)
  // window.api = api;
  // @ts-ignore (define in dts)
  window.ipcRenderer = ipc;
  window.control = {
    peer: peer,
    setRemote: setRemote,
  };
}
